# -*- coding:utf-8 -*-
import argparse, os, json

class CharlesMacFormat(object):
    '''
    格式化charles 存储的session json文件
    '''
    def __init__(self):
        print('''
            ==========================================
            欢迎使用格式化 
            eg: python3.6 --from dir --to dir
            form: 从某个路径下导入到to目录，取出目标json文件。
        ''')

    def run(self, from_dir='', to_dir=""):
        if os.path.isdir(from_dir) == False:
            print('目标文件夹不是存在')
            os._exit(1)

        if os.path.isdir(to_dir) == False:
            print('导入文件夹不存在')
            os._exit(1)

        from_json_dir = []
        for tmp in os.listdir(from_dir):
            from_json_dir.append(os.path.join(from_dir, tmp))

        # 读取文件
        if from_json_dir == []:
            print('目标文件夹没有读取到文件！！！')
            os._exit(1)

        # 只有这5个path才会有视频列表
        allow_path = [ '/aweme/v1/feed/', '/aweme/v1/aweme/post/', '/aweme/v1/aweme/favorite/', '/aweme/v1/nearby/feed/','/aweme/v1/music/aweme/']

        print('log: 开始导入文件')
        for file in from_json_dir:
            if os.access(file, os.R_OK) == False:
                print('error: ', file, '文件没有读取权限')
                continue
            json_data = []
            file_name = os.path.basename(file)

            try:
                with open(file) as content:
                    json_data = json.load(content)
            except:
                print('error: ', file, '文件读取失败')
                continue

            for key,tmp in enumerate(json_data):
                # 判断host
                if tmp['host'] != "aweme.snssdk.com":
                    continue
                if tmp['path'] not in allow_path:
                    continue


                try:
                    json_save_content = tmp['response']['body']['text']
                except:
                    continue
                tmp_file_name = file_name + "__" + str(key)
                with open(os.path.join(to_dir, tmp_file_name), 'w') as f:
                    f.write(json_save_content)
                    print('log: 文件:' + tmp_file_name + ',导入完成')

        print('log: 操作完成')


if __name__ == '__main__':
    charles_tool = CharlesMacFormat()
    parser = argparse.ArgumentParser()
    parser.add_argument("--where", help="目标文件夹", type=str)
    parser.add_argument("--to", help="导入文件夹", type=str)
    args = parser.parse_args()
    charles_tool.run(args.where, args.to)